<template>
  <div style="padding: 5px 20px;">
    <br>
    <el-form :inline="true" :model="listQuery" class="demo-form-inline">
      <el-form-item label="问答对名称">
        <el-input v-model="listQuery.unit_name" placeholder="请输入问答对名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData">
          <template #icon>
            <el-icon><Search /></el-icon>
          </template>
          查询
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="TJCollectionForm">
          <template #icon>
            <el-icon><Edit /></el-icon>
          </template>
          添加
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 表格-->
    <el-table :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="问答对ID" width="50" type="index">
      </el-table-column>
      <el-table-column label="对应景区" prop="jq">
      </el-table-column>
      <el-table-column label="问题" prop="question">
      </el-table-column>
      <el-table-column label="答案" prop="answer">
        <template v-slot="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.answer" placement="top">
            <div class="answer-text">{{ scope.row.answer }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="上次操作时间">
        <template v-slot="scope">
          <el-icon><Clock /></el-icon>&nbsp;
          <span style="margin-left: 5px" v-text="formatDateTime(scope.row.last_operation_time)"></span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template v-slot="scope">
          <el-tooltip class="item" effect="dark" content="修改" placement="top">
            <el-button type="primary" circle @click="BJCollectionForm(scope.$index)">
              <el-icon><Edit /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button type="danger" circle @click="deleteVisible(scope.row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
                   :page-sizes="[10]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"
                   :background="true">
    </el-pagination>

    <el-dialog :title="textMap[dialogStatus]" v-model="dialogFormVisible">
      <el-form ref="collectionform" :rules="rules" :model="ruleForm" label-width="120px" label-position="left">
        <el-form-item label="对应景区" prop="jq" v-if="dialogStatus=='create'">
          <el-select v-model="ruleForm.jq" placeholder="请选择景点" >
            <el-option
              v-for="spot in scenicSpots"
              :key="spot.value"
              :label="spot.label"
              :value="spot.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题" prop="question" v-if="dialogStatus=='create'">
          <el-input placeholder="问题" v-model="ruleForm.question"></el-input>
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input placeholder="答案" v-model="ruleForm.answer"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" v-if="dialogStatus=='create'" @click="submitCollectionForm('collectionform')">添 加</el-button>
        <el-button type="warning" v-else @click="updateCollectionForm('collectionform')">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Search, Edit, Clock, Delete } from '@element-plus/icons-vue';
import { useCookies } from 'vue3-cookies';
import { ref } from 'vue';
import axios from 'axios';

export default {
  name: 'department',
  components: {
    Search,
    Edit,
    Clock,
    Delete
  },
  created() {
    this.fetchScenicSpotTypes();
  },
  mounted() {
    this.fetchData();
  },
  data() {
    return {
      listLoading: false,
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        unit_name: '',
      },

      scenicSpots: [],
      dialogFormVisible: false,
      dialogStatus: 'create',
      textMap: {
        update: '修改问答对',
        create: '添加问答对'
      },
      ruleForm: {
        answer: '',
        jq: '',
        last_operation_time: '',
        qa_id: '',
        question: '',
      },
      rules: {
        jq: [{
          required: true,
          validator: this.checkJq,
          message: '请输入对应景区',
          trigger: 'blur'
        }],
        question: [{
          required: true,
          message: '请输入问题',
          trigger: 'blur'
        }],
        answer: [{
          required: true,
          message: '请输入答案',
          trigger: 'blur'
        }]
      }
    };
  },
  methods: {
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.fetchData();
    },
    fetchScenicSpotTypes() {
      axios.get('http://127.0.0.1:8000/qa/get-scenic-spot-types1/')
        .then(response => {
          console.log(response.data);
          this.scenicSpots = response.data.scenic_spot_ids.map(item => ({
            value: item,
            label: item
          }));
        })
        .catch(error => {
          console.error('获取景点信息失败', error);
        });
    },
    fetchData() {
      this.listLoading = true;
      axios.get('http://127.0.0.1:8000/qa/qa-pairs/', {
        params: {
          page: this.listQuery.page,
          limit: this.listQuery.limit,
          keyword: this.listQuery.unit_name
        }
      }).then(response => {
        this.listLoading = false;
        this.list = response.data.results;
        this.total = response.data.count;
      }).catch(error => {
        console.error('Error fetching data:', error);
        this.listLoading = false;
      });
    },
    TJCollectionForm() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        console.log('dialogFormVisible:', this.dialogFormVisible);
      });
    },
    resetForm() {
      this.ruleForm = {
        answer: '',
        jq: '',
        last_operation_time: '',
        qa_id: '',
        question: '',
      };
    },
    BJCollectionForm($index) {
      this.ruleForm = JSON.parse(JSON.stringify(this.list[$index]));
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
    },
    submitCollectionForm(formname) {
      this.$refs[formname].validate((valid) => {
        if (valid) {
          axios.post('http://127.0.0.1:8000/qa/addqa-paired/', this.ruleForm).then(response => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$message.success('添加数据成功！');
          }).catch(error => {
            console.error('Error submitting data:', error);
            this.$message.error('添加数据失败！');
          });
        } else {
          console.log('error submit!');
          return false;
        }
      });
    },
    updateCollectionForm(formname) {
      this.$refs[formname].validate((valid) => {
        if (valid) {
          axios.put(`http://127.0.0.1:8000/qa/update/${this.ruleForm.qa_id}/`, this.ruleForm).then(response => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$message.success('修改数据成功！');
          }).catch(error => {
            console.error('Error updating data:', error);
            this.$message.error('修改数据失败！');
          });
        } else {
          console.log('error submit!');
          return false;
        }
      });
    },
    deleteVisible(scope) {
      const csrfToken = this.$cookies.get('csrftoken');
      if (!csrfToken) {
        console.error('CSRF token not found');
        this.$message.error('CSRF token not found');
        return;
      }

      this.$confirm(`确定要删除 ${scope.qa_id} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const url = `http://127.0.0.1:8000/qa/delete/${scope.qa_id}/`;
        this.$axios.delete(url, { withCredentials: true, headers: { 'X-CSRFToken': csrfToken } })
          .then(response => {
            this.fetchData();
            this.$message.success('删除成功');
          })
          .catch(error => {
            console.error('Error:', error);
            this.$message.error('删除数据失败！请检查网络连接或重试。');
            if (error.response && error.response.status === 403) {
              this.$message.error('CORS 策略阻止了请求。请检查后端配置。');
            }
          });
      }).catch(() => {
        // 用户取消删除
      });
    },
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  }
}
</script>
<style>
.answer-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

</style>
